package com.gouda.temporary.controller;

import com.gouda.temporary.context.ContextCode;
import com.gouda.temporary.service.InviteLogService;
import com.gouda.temporary.service.WeiXinService;
import com.gouda.temporary.utils.CacheUtils;
import com.gouda.temporary.utils.CommonUtils;
import com.gouda.temporary.utils.ConfigUtils;
import com.gouda.temporary.utils.XYHttpUtils;
import com.gouda.temporary.vo.BaseVO;
import com.gouda.temporary.vo.InviteLog;
import com.gouda.temporary.vo.TempHourOrders;
import com.gouda.temporary.vo.openwx.InvitInfo;
import com.gouda.temporary.vo.openwx.WxOwnerInfo;
import com.qq.weixin.mp.aes.WXBizMsgCrypt;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping(value = "/invite")
public class InviteController {

    private static final Logger log = LoggerFactory.getLogger(InviteController.class);

    @Resource
    private InviteLogService inviteLogService;

    @Resource
    private WeiXinService weiXinService;

    @ModelAttribute
    public void init(ModelMap model, HttpServletRequest request) {
        model.put("ctx", request.getContextPath());
    }


    /**
     * 邀请二维码页面
     */
    @RequestMapping(value = "/qrcode")
    public ModelAndView InvestQrcode(HttpServletRequest request) {
        // 获取微信回调信息参数
        String code = request.getParameter("code");
       log.info(">>>> 邀请页面 code={}", code);
        // 通过微信接口获取业主信息
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("code",code);
        return new ModelAndView("invitation", map);
    }


    /**
     * 邀请二维码扫描后跳转页面
     */
    @RequestMapping(value = "/inviteform")
    public ModelAndView Investform(HttpServletRequest request) {
        // 获取微信回调信息参数
        String code = request.getParameter("code");
        log.info(">>>>Inviteform  code={}", code);

        Map<String, Object> map = new HashMap<String, Object>();
        map.put("code",code);
        return new ModelAndView("invitationForm", map);
    }
    /**
     * 保存并创建微信用户信息
     */
    @RequestMapping(value = "/invitesubmit")
    @ResponseBody
    public ModelAndView Invitesubmit(HttpServletRequest request,
                                     @RequestParam(value="mobile") String mobile,
                                     @RequestParam(value="name") String name,
                                     @RequestParam(value="placeno") String placeno
                                     ){
        //@RequestBody String data
        // 获取微信回调信息参数
        Map<String, Object> map = new HashMap<String, Object>();
        try {
            String code = request.getParameter("code");
            log.info(">>>> Invitesubmit code={}", code);
            // 通过微信接口获取业主信息
            WxOwnerInfo wxOwnerInfo = weiXinService.takeOwnerInfo(code);
            if (!ContextCode.WX_OK.equals(wxOwnerInfo.getErrcode())) {

            }
            String userid =mobile;
            InvitInfo invitInfo = new InvitInfo();
            invitInfo.setUserid(userid);
            invitInfo.setName(name);
            invitInfo.setDepartment("9");
            invitInfo.setMobile(mobile);
            /*String PostJson ="{\n" +
                "   \"userid\": \"zhangsan\",\n" +
                "   \"name\": \"张三\",\n" +
                "   \"department\": [1,2],\n" +
                "   \"mobile\": \"15913215421\"" +
                "}\n"; */
            String url = "https://qyapi.weixin.qq.com/cgi-bin/user/create?access_token=" + CacheUtils.getCachedAccessToken();
            String returnjson = XYHttpUtils.doPost(url, CommonUtils.gsonToJson(invitInfo));
            log.info("Logcode:"+CommonUtils.gsonToJson(invitInfo) +"|"+wxOwnerInfo);
            BaseVO bv = CommonUtils.gsonParseObject(returnjson, BaseVO.class);

            if (bv.getErrmsg().equals("created")) {
                InviteLog inviteLog = new InviteLog();
                inviteLog.setInviteId(wxOwnerInfo.getUserid());
                inviteLog.setInviteName(wxOwnerInfo.getName());
                inviteLog.setInviteUserId(userid);
                inviteLog.setInviteUserName(name);
                inviteLog.setInviteUserPhone(mobile);
                inviteLog.setInviteUserPlaceNO(placeno);
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                inviteLog.setInviteTime(sdf.format(new Date()));
                inviteLog.setIffollow(0);
                inviteLogService.addInvite(inviteLog);
                map.put("success", "1");
            } else {
                map.put("success", "2");
            }
        }catch (Exception ex){ map.put("success", "0");log.error(ex.toString());}
        String corpid = ConfigUtils.getCorpID();
        String secret = ConfigUtils.getCorpSecret();
        map.put("corpid",corpid);
        map.put("secret",secret);
        return new ModelAndView("invitationSubmit", map);
    }
    /**
     * 获取邀请列表
     */
    @RequestMapping(value = "/invitelist")
    @ResponseBody
    public ModelAndView Invitelist(HttpServletRequest request){
        // 获取微信回调信息参数
        String code = request.getParameter("code");
        List<InviteLog> lv=null;
        if(code!=null){


        log.info(">>>> Invitesubmit code={}", code);
        // 通过微信接口获取业主信息
        WxOwnerInfo wxOwnerInfo = weiXinService.takeOwnerInfo(code);
        if (!ContextCode.WX_OK.equals(wxOwnerInfo.getErrcode())) {
        }
            lv =inviteLogService.selectInvite(wxOwnerInfo.getUserid());
        }
        else
        {
            String inviteid = request.getParameter("inviteid");
            lv =inviteLogService.selectInvite(inviteid);
        }
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("InviteLogList",lv);
        return new ModelAndView("invitlist", map);
    }
    /**
     * 获取邀请明细
     */
    @RequestMapping(value = "/invitedetail")
    @ResponseBody
    public ModelAndView Invitedetail(HttpServletRequest request){
        // 获取微信回调信息参数
        String code = request.getParameter("code");
        Integer Id = Integer.valueOf(request.getParameter("Id"));
        log.info(">>>> Invitesubmit code={}", code);
        // 通过微信接口获取业主信息
        WxOwnerInfo wxOwnerInfo = weiXinService.takeOwnerInfo(code);
        if (!ContextCode.WX_OK.equals(wxOwnerInfo.getErrcode())) {

        }
        InviteLog inviteLog =inviteLogService.selectInvitebyid(Id);
        log.info("" + wxOwnerInfo);
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("inviteLog",inviteLog);
        return new ModelAndView("invitdetail", map);
    }
   /* private void sendWorkerSnatchSuccess(String workerId, String orderNo, String ownerMessage, String createDate) {
        String title = "抢单成功";
        String xsDescription = buildLss(ownerMessage) + "\n\n派单时间: " + createDate;
        String url = "http://gouda3.xinleju.cn:8080/gouda-jm/temp/order-detail.do?userType=2&orderId=" + orderNo;
        weiXinService.sendNewsMsgToWorker(workerId, title, xsDescription, url);
    }*/
}

